package com.demo.redis.multi;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Component;

@Component
public class MultiService implements Runnable, InitializingBean {

    @Autowired
    private RedisTemplate redisTemplate;
    public static String key = "multiKey";
    @Override
    public void run() {
        Integer result = (Integer) redisTemplate.execute(new SessionCallback<Integer>() {
            @Override
            public Integer execute(RedisOperations operations) throws DataAccessException {
                int intValue = 0;
                String keyValue = (String) operations.opsForValue().get(key);
                if (keyValue != null){
                    System.out.println(keyValue);
                    intValue = Integer.valueOf(keyValue);
                }
                intValue +=1;
                operations.opsForValue().set(key,intValue);
                return intValue;
            }
        });
        System.out.println("result : "+result);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        redisTemplate.delete(key);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(this::run);
            thread.start();
        }
    }
}
